/*
 * @Author: 杨波Amani 2474320177@qq.com
 * @Date: 2023-10-19 11:47:13
 * @LastEditors: 杨波Amani 2474320177@qq.com
 * @LastEditTime: 2023-11-06 11:20:47
 * @FilePath: \dolphin-scheduler-admin\src\router\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * @Author: yangboSam yangbo_sam@foxmail.com
 * @Date: 2023-10-17 14:26:55
 * @LastEditors: 杨波Amani 2474320177@qq.com
 * @LastEditTime: 2023-11-06 10:57:29
 * @FilePath: \dplphinscheduler\src\router\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {
  createRouter,
  createWebHistory,
  NavigationGuardNext,
  RouteLocationNormalized
} from 'vue-router'
import routes from './routes'
import pinia from '@/store/store'
import { getUserInfo } from '@/service/modules/users'
import { useUserStore } from '@/store/user/user'
import type { UserInfoRes } from '@/service/modules/users/types'


// NProgress
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const router = createRouter({
  history: createWebHistory(
    import.meta.env.MODE === 'production' ? '/dolphinscheduler/ui/' : '/'
  ),
  routes
})

interface metaData {
  title?: string
  activeMenu?: string
  showSide?: boolean
  auth?: Array<string>
}

const parseURLParams = function(url:any) {
  const params:any = new URLSearchParams(url);
  const keyValues = params.entries();
  const result:any = {};

  for (const [key, value] of keyValues) {
    result[key] = value;
  }

  return result;
}

/**
 * Routing to intercept
 */
router.beforeEach(
  async (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext
  ) => {
    const urlSearch = to.fullPath.split("?")[1];
    NProgress.start()
    const userStore = useUserStore(pinia)
    const metaData: metaData = to.meta
    if (urlSearch) {
      const params = parseURLParams(urlSearch)
      if (params.sessionId) {
        userStore.setSessionId(params.sessionId)
        userStore.setSecurityConfigType(params.securityConfigType)
        // userStore.setUserInfo({
        //     "id": 1,
        //     "userName": "admin",
        //     "userPassword": "7ad2410b2f4c074479a8937a28a22b8f",
        //     "email": "xxx@qq.com",
        //     "phone": "",
        //     "userType": "ADMIN_USER",
        //     "tenantId": 2,
        //     "state": 1,
        //     "tenantCode": null,
        //     "queueName": null,
        //     "alertGroup": null,
        //     "queue": "",
        //     "timeZone": "Asia/Shanghai",
        //     "createTime": "2023-08-04 23:44:33",
        //     "updateTime": "2023-10-20 11:36:30"
        // })

        const userInfoRes: UserInfoRes = await getUserInfo()
        userStore.setUserInfo(userInfoRes)
        userStore.setHideNavbar(params.hideNavbar == 'true' ? true : false)
        userStore.setHideSider(params.hideSider == 'true' ? true : false)
      }
      next()
    } else if (
      metaData.auth?.includes('ADMIN_USER') &&
      (userStore.getUserInfo as UserInfoRes).userType !== 'ADMIN_USER' &&
      metaData.activeMenu === 'security'
    ) {
      to.fullPath = '/security/token-manage'
      next({ name: 'token-manage' })
    } else {
      next()
    }

    NProgress.done()
  }
)

router.afterEach(() => {
  NProgress.done()
})

export default router
